package com.sangeng.service.impl;

import com.aliyun.oss.model.CannedAccessControlList;
import com.sangeng.domain.OssResult;
import com.sangeng.domain.ResponseResult;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class ossService {

    public OssResult Demo(MultipartFile multipartFile) throws  Exception {

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-chengdu.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5t6DLY7X3U6NeuUmxMYq";
        String accessKeySecret = "TJkGbb3O7AczvVAGLcKZ50TZV4CCFR";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "imgtw";


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            if(!ossClient.doesBucketExist(bucketName)){ //如果不存在这个桶，会自动创建
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置oss实例的访问权限,公共读
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }

            //2.获取文件的流
            InputStream fileInputStream = multipartFile.getInputStream();
            //3.构建日期目录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String dataPath = dateFormat.format(new Date());

            //4，开始组装我们自己定义的文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String filename = UUID.randomUUID().toString();
            String suffix =originalFilename.substring(originalFilename.lastIndexOf("."));
            String newName=filename+suffix;
            //完整文件名字
            String finalNameUrl=dataPath+"/"+newName;

            //以流的形式向桶里面写进去 imgtw/data/filename ....就够成了多层目录分隔
            ossClient.putObject(bucketName, finalNameUrl, fileInputStream);
//            return "http://"+bucketName+"."+endpoint+"/"+finalNameUrl;
            Map map = new HashMap<>();
            map.put("url","http://"+bucketName+"."+endpoint+"/"+finalNameUrl);

            return new OssResult<>(0,map);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            return  new OssResult(1,"文件上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
